import qs from 'qs'
// 导出
import axios from 'axios'
import { baseUrl } from '@/Utils/url.js'

export function getRequest (name, src = '') {
  const url = src || window.location.href
  const [, search] = url.split('?')
  return search ? qs.parse(search)[name] || '' : ''
}

export function exportExcel (data, name) {
  let blob = new Blob([data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8'}) // 设置文件类型excel
  let url = window.URL.createObjectURL(blob) // 创建一个临时的url指向blob对象
  // 创建url之后可以模拟对此文件对象的一系列操作，例如：预览、下载
  let a = document.createElement('a')
  a.href = url
  a.download = name + '.xlsx'
  a.click()
  // 释放这个临时的对象url
  window.URL.revokeObjectURL(url)
}

export let instance = axios.create({
  timeout: 100000,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
    responseType: 'arraybuffer'
  },
  responseType: 'arraybuffer'
})
instance.interceptors.request.use(
  config => {
    let token = window.localStorage.getItem('accessToken')
    if (token) config.headers.common['iot-Auth'] = 'bearer ' + token
    return config
  },
  err => {
    return Promise.reject(err)
  }
)
if (process.env.NODE_ENV === 'production') {
  instance.defaults.baseURL = baseUrl
}
export const fileDownload = (url, data) =>
  instance.get(url, { params: data }).then(response => {
    const f = response.headers['Content-Disposition'] || response.headers['content-disposition']
    const type = response.headers['Content-Type'] || response.headers['content-type']
    const fileName = f.match(/filename=(.*)/)[1]
    // 将二进制流转为blob
    const blob = new Blob([response.data], {
      type
    })
    if (typeof window.navigator.msSaveBlob !== 'undefined') {
      // 兼容IE，window.navigator.msSaveBlob：以本地方式保存文件
      window.navigator.msSaveBlob(blob, decodeURI(fileName))
    } else {
      // 创建新的URL并指向File对象或者Blob对象的地址
      const blobURL = window.URL.createObjectURL(blob)
      // 创建a标签，用于跳转至下载链接
      const tempLink = document.createElement('a')
      tempLink.style.display = 'none'
      tempLink.href = blobURL
      tempLink.setAttribute('download', decodeURI(fileName))
      // 兼容：某些浏览器不支持HTML5的download属性
      if (typeof tempLink.download === 'undefined') {
        tempLink.setAttribute('target', '_blank')
      }
      // 挂载a标签
      document.body.appendChild(tempLink)
      tempLink.click()
      document.body.removeChild(tempLink)
      // 释放blob URL地址
      window.URL.revokeObjectURL(blobURL)
    }
  })

//  监控进度
export const progressDownLoad = ({url, data}) => {
  instance({method: 'get',
    url,
    params: data,
    onDownloadProgress: (evt) => {
      console.log(evt)
    }}).then(response => {
    const f = response.headers['Content-Disposition'] || response.headers['content-disposition']
    const type = response.headers['Content-Type'] || response.headers['content-type']
    const fileName = f.match(/filename=(.*)/)[1]
    // 将二进制流转为blob
    const blob = new Blob([response.data], {
      type
    })
    if (typeof window.navigator.msSaveBlob !== 'undefined') {
      // 兼容IE，window.navigator.msSaveBlob：以本地方式保存文件
      window.navigator.msSaveBlob(blob, decodeURI(fileName))
    } else {
      // 创建新的URL并指向File对象或者Blob对象的地址
      const blobURL = window.URL.createObjectURL(blob)
      // 创建a标签，用于跳转至下载链接
      const tempLink = document.createElement('a')
      tempLink.style.display = 'none'
      tempLink.href = blobURL
      tempLink.setAttribute('download', decodeURI(fileName))
      // 兼容：某些浏览器不支持HTML5的download属性
      if (typeof tempLink.download === 'undefined') {
        tempLink.setAttribute('target', '_blank')
      }
      // 挂载a标签
      document.body.appendChild(tempLink)
      tempLink.click()
      document.body.removeChild(tempLink)
      // 释放blob URL地址
      window.URL.revokeObjectURL(blobURL)
    }
  })
}
